package com.spark.starter.service.impl;

import com.spark.starter.prop.IpStarterProperties;
import com.spark.starter.service.IpStarterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author sc
 * @DATE 2024/6/4 22:44
 * @Description:
 * @Version 1.0
 */
@Slf4j
public class IpStarterServiceImpl implements IpStarterService {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private IpStarterProperties ipStarterProperties;

    private Map<String,Integer> map =  new HashMap<>();

    /**
     *  根据Ip统计访问次数
     */
    @Override
    public Map<String,Integer> records() {
        String ip = httpServletRequest.getRemoteAddr();
        Integer ips = map.get(ip);
        if (ObjectUtils.isEmpty(ips)){
            map.put(ip,1);
        }else {
            map.put(ip,++ips);
        }
        map.forEach((key,value) -> {
            if (ipStarterProperties.getDisplay().equals(IpStarterProperties.DisplayMode.DETAIL.getVlaue())){
                log.info("======================================");
                log.info("当前IP地址为{},访问次数为{}",key,value);
                log.info("======================================");
            }else {
                log.info("当前IP地址为{},访问次数为{}",key,value);
            }
        });

        return map;

    }
}
